package com.slipper.sfts.member.service;

import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.slipper.common.util.MD5;
import com.slipper.common.util.StringUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import com.slipper.sfts.member.dao.MemberDao;
import com.slipper.sfts.api.member.bo.MemberBO;

import com.slipper.common.transaction.ReadTransactional;
import com.slipper.common.transaction.WriteTransactional;
import com.slipper.common.util.Tool;

@Service
@ReadTransactional
public class MemberService {
    @Resource
    private MemberDao memberDao;
    @Resource
    private MemberBrokerAccountService memberBrokerAccountService;

    public MemberBO queryBy(String id) {
        return memberDao.queryBy(id);
    }

    public List<MemberBO> queryList(MemberBO bo) {
        return memberDao.queryList(bo);
    }
    
    public PageInfo<MemberBO> queryPage(MemberBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(memberDao.queryList(bo));
    }
    
    @WriteTransactional
    public int save(MemberBO bo) {
        int result;
        if (!StringUtil.isBlank(bo.getPassword())) {
            bo.setPassword(MD5.encode(bo.getPassword()));
        }
        if (bo.getId() != null && !"".equals(bo.getId())) {
            result = memberDao.update(bo);
        } else {
            bo.setId(Tool.getUUID());
            result = memberDao.insert(bo);
        }

        bo.getAccountList().forEach(account -> {
            account.setFreezeMoney(null);
            account.setMarketMoney(null);
            account.setProfitMoney(null);
            account.setTotalAssets(null);
        });
        return result + memberBrokerAccountService.save(bo.getId(), bo.getAccountList(), bo.getCreateId());
    }
    
    @WriteTransactional
    public int delete(MemberBO bo) {
        return memberDao.delete(bo);
    }

    public MemberBO queryByLogin(MemberBO bo) {
        return memberDao.queryByLogin(bo);
    }
}
